//
//  HKPieChartView.m
//  PieChart
//
//  Created by hukaiyin on 16/6/20.
//  Copyright © 2016年 HKY. All rights reserved.
//

#import "HKPieChartView.h"

@interface HKPieChartView()<CAAnimationDelegate>

@property (nonatomic, strong) CAShapeLayer *trackLayer;
@property (nonatomic, strong) CAShapeLayer *progressLayer; 
@property (nonatomic, assign) CGFloat lineWidth;
@property (nonatomic, strong) UIBezierPath *path;
@property (nonatomic, assign) CGFloat percent; //饼状图显示的百分比，最大为100
@property (nonatomic, assign) CGFloat animationDuration;//动画持续时长
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) CGFloat pathWidth;
@property (nonatomic, strong) UILabel *progressLabel;

@end

@implementation HKPieChartView

#pragma mark - Life Cycle

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self updateUI];
    }
    return self;
}

-(void)awakeFromNib {
    [super awakeFromNib];
    [self updateUI];
}

- (void)updateUI {
    self.animationDuration = 3;
    self.pathWidth = self.bounds.size.width / 1.15;
    
    [self trackLayer];
    [self progressLayer];
}

- (void)dealloc {
    [self invalidateTimer];
}

- (void)removeFromSuperview {
    [super removeFromSuperview];
    [self invalidateTimer];
}

#pragma mark - Load 这个被调用两次.
/**作用:设置CAShapeLayer相关属性*/
- (void)loadLayer:(CAShapeLayer *)layer WithColor:(UIColor *)color {
    
    CGFloat layerWidth = self.pathWidth;
    CGFloat layerX = (self.bounds.size.width - layerWidth)/2;
    layer.frame = CGRectMake(layerX, layerX, layerWidth, layerWidth);
    layer.fillColor = [UIColor clearColor].CGColor;
    layer.strokeColor = color.CGColor;
    layer.lineCap = kCALineCapButt;
    layer.lineWidth = self.lineWidth;
    layer.path = self.path.CGPath;
}

#pragma mark - Animation
- (void)updatePercent:(CGFloat)percent animation:(BOOL)animationed {
    self.percent = percent;
    [self.progressLayer removeAllAnimations];
    
    if (!animationed) { 
        // 事物组动画
        [CATransaction begin];
        [CATransaction setDisableActions:YES];
        [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
        [CATransaction setAnimationDuration:1];
        
        self.progressLayer.strokeEnd = self.percent / 100.0; // 设置CAShapeLayer的结束值
        
        [CATransaction commit];
    } else {
        // 走的是这一段动画
        // 基础动画
        CABasicAnimation *animation= [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        animation.fromValue = @(0.0);
        animation.toValue = @(self.percent / 100.);
        animation.duration = self.animationDuration * self.percent / 100; // 设置动画间隔;
        animation.removedOnCompletion = YES;
        animation.delegate = self;

        self.progressLayer.strokeEnd = self.percent / 100.0;  //这一行代码, 不写, 动画结束显示的就是底色, 白色;加上就是动画的颜色
        [self.progressLayer addAnimation:animation forKey:@"strokeEndAnimation"]; // 关键:这一行代码决定他动还是不懂
    }
}

#pragma mark - CAAnimationDelegate
/**Tells the delegate the animation has started. 告诉代理动画开始了*/
// 开启定时器
- (void)animationDidStart:(CAAnimation *)anim {
    self.timer = [NSTimer timerWithTimeInterval:1/60.f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
/**告诉代理动画结束了*/
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    if (flag) {
        [self invalidateTimer];
    }
}

/**定时器里面的方法*/
- (void)timerAction {
    id strokeEnd = [[_progressLayer presentationLayer] valueForKey:@"strokeEnd"];
    if (![strokeEnd isKindOfClass:[NSNumber class]]) {
        return;
    }
    CGFloat progress = [strokeEnd floatValue];
    self.progressLabel.text = [NSString stringWithFormat:@"%0.f%%",floorf(progress * 100)]; //有用: 这行代码决定了百分比是否显示,
    
    // 调用block将进度传出去, 使用block之前先做判断空处理
    if (self.progressBlock != nil) {
        self.progressBlock(self.progressLabel.text); // 调用block传值
    }
}


- (void)invalidateTimer {
    if (!self.timer) {
        return;
    }
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark - Getters & Setters

- (CAShapeLayer *)trackLayer {
    if (!_trackLayer) {
        _trackLayer = [CAShapeLayer layer];
        [self loadLayer:_trackLayer WithColor:[UIColor whiteColor]]; // 调用一次
        [self.layer addSublayer:_trackLayer];
    }
    return _trackLayer;
}

- (CAShapeLayer *)progressLayer {
    if (!_progressLayer) {
        _progressLayer = [CAShapeLayer layer];
        
        UIColor *lightBlue =  [UIColor colorWithRed:0.310 green:0.627 blue:0.984 alpha:1.000]; // 浅蓝色

        [self loadLayer:_progressLayer WithColor:lightBlue]; // 调用第二次
        _progressLayer.strokeEnd = 0;
        [self.layer addSublayer:_progressLayer];
    }
    return _progressLayer;
}

- (UILabel *)progressLabel {
    if (!_progressLabel) {
        _progressLabel = [[UILabel alloc]initWithFrame:self.bounds];
//        _progressLabel.textColor = [UIColor colorWithRed:0.310 green:0.627 blue:0.984 alpha:1.000];// 浅蓝色
        _progressLabel.textColor = [UIColor whiteColor];
        _progressLabel.textAlignment = NSTextAlignmentCenter;
        _progressLabel.font = [UIFont systemFontOfSize:38];

        [self addSubview:_progressLabel];
    }
    return _progressLabel;
}

- (void)setPercent:(CGFloat)percent {
    _percent = percent;
    _percent = _percent > 100 ? 100 : _percent;
    _percent = _percent < 0 ? 0 : _percent;
    NSLog(@"%-.4f",_percent);
}

- (UIBezierPath *)path {
    if (!_path) {
        
        CGFloat halfWidth = self.pathWidth / 2;
        _path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(halfWidth, halfWidth) radius:(self.pathWidth - self.lineWidth)/2 startAngle:-M_PI/2*3 endAngle:M_PI/2 clockwise:YES];
    }
    return _path;
}

- (CGFloat)lineWidth {
    if (_lineWidth == 0) {
        _lineWidth = 5;
    }
    return _lineWidth;
}
#pragma mark 问题
/*
 1.有几个新类, 看不懂,
 2.没看懂逻辑关系
 3.看的心烦意乱,想kuan东西. 
 4.安慰的话:静下心来,研究研究,涨知识呀
 应为我不会所以我才学., 越不会越去看, 我就是不信邪, 代码都给你了. 你只管改改改. 看懂了就可以改改改改改改了, 想咋改就咋改. 
 5.这种代码可以用一句话来形容:垃圾,封装的太牛逼了, 看不懂逻辑, 才200行代码是真心看不懂哎呀. 看的很痛苦, 注释也没跌, 马丹
 6.这个搞不懂:老爱重写setter/getter 方法干莫洛,还爱在getter方法中给变量赋值,作者是傻逼,  
 
 */
@end
